package shapewar.engine.calc;

public class Calc {
	public boolean canFire(Pos pa,Pos pb,Pos pc,float angle){
		float a = calcDistance(pb, pc);
		float b = calcDistance(pa, pc);
		float c = calcDistance(pa, pb);
		return Math.acos((b*b+c*c-a*a)/(2*b*c))*180/Math.PI<angle;
	}
	
	public float calcAngle(Pos pos1,Pos pos2) {
		float dx = pos2.x - pos1.x;
		float dy = pos2.y - pos1.y;
		return -(float)(Math.atan2(dy, dx) * 180 / Math.PI);
	}
	
	public float calcDistance(Pos pos1,Pos pos2) {
		return (float)Math.sqrt((pos2.x-pos1.x)*(pos2.x-pos1.x) + (pos2.y-pos1.y)*(pos2.y-pos1.y));
	}
	
	public void move(Pos pos,float angle,float speed){
		pos.x += speed * Math.cos(angle * Math.PI / 180);
		pos.y += speed * -Math.sin(angle * Math.PI / 180);
	}
 
	public boolean hitTest(Pos pos1,Pos pos2,float dis){
		if(calcDistance(pos1, pos2)>dis)return false;
		return true;
	}
	
	public boolean hitTest(Pos pos1,Pos v_pos,float v[][],float dis){
		if(calcDistance(pos1, v_pos)>dis)return false;
		boolean hitted = false;
		int p_left=0,p_right=0;
		float pos_x = v_pos.x,pos_y = v_pos.y;
		for(int i=0;i<v.length;i++){
			double xa=v[i][0] + pos_x;
			double ya=v[i][1] + pos_y;
			double xb=v[(i+1)%v.length][0] + pos_x;
			double yb=v[(i+1)%v.length][1] + pos_y;
			if((pos1.y-ya)*(pos1.y-yb)<0){
				double tx = xa+(pos1.y-ya)/(yb-ya)*(xb-xa);
				if(tx<pos1.x){
					p_left++;
				}else{
					p_right++;
				}
			}
		}
		if(p_left%2==1&&p_right%2==1){
			hitted=true;
		}else{
			hitted=false;
		}
		return hitted;
	}
	
	public boolean hitTest(Pos v1_pos,Pos v2_pos,float v1[][],float v2[][],float dis){
		if(calcDistance(v1_pos, v2_pos)>dis)return false;
		Pos tmp = new Pos();
		for(int i=0;i<v1.length;i++){
			tmp.x = v2[i][0];
			tmp.y = v2[i][1];
			if(hitTest(tmp, v1_pos, v1, dis))
				return true;
		}
		for(int i=0;i<v2.length;i++){
			tmp.x = v1[i][0];
			tmp.y = v1[i][1];
			if(hitTest(tmp, v2_pos, v2, dis))
				return true;
		}
		return false;
	}
	
}
